import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import dayjs from "dayjs";
import { dateAdd } from "@/utils/libs";
const { VITE_PUBLIC_PATH } = import.meta.env;

export type UserResult = {
  success: boolean;
  data: {
    /** 用户id【经销商id】 */
    userId: number;
    /** 头像 */
    avatar: string;
    /** 用户名 */
    username: string;
    /** 昵称 */
    nickname: string;
    /** 当前登录用户的角色 */
    roles: Array<string>;
    /** 按钮级别权限 */
    permissions: Array<string>;
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
  info: string;
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

/** 登录 */
export const getLogin = (data?: object) => {
  return new Promise<UserResult>((resolve, reject) => {
    http
      .request("post", changeHttpLink("/api/Auth/admin_login"), {
        data
      })
      .then((res: any) => {
        if (res.Success) {
          res.Data.avatar = VITE_PUBLIC_PATH + "static/img/avatar.png";
          const expire = dateAdd("m", -5, new Date(res.Data.Expiration));
          resolve({
            success: true,
            //@ts-ignore
            data: {
              userId: res.Data.Id,
              avatar: res.Data.Avatar,
              username: res.Data.UserName,
              nickname: res.Data.NickName,
              roles: [],
              permissions: [],
              accessToken: res.Data.Token,
              refreshToken: res.Data.Token,
              //@ts-ignore
              expires: dayjs(expire).format("YYYY-MM-DD HH:mm:ss")
            },
            info: res.Message
          });
        } else {
          resolve({
            success: false,
            info: res.Message
          });
        }
      })
      .catch(err => {
        reject(err);
      });
  });
};

/* 测试模拟登录 */
// export const getLogin = (data?: object) => {
//   return new Promise<UserResult>(resolve => {
//     // 模拟延迟，更接近真实请求体验
//     setTimeout(() => {
//       // 模拟响应数据
//       const mockRes = {
//         Success: true,
//         Data: {
//           Avatar: VITE_PUBLIC_PATH + "static/img/avatar.png",
//           UserName: data?.["username"] || "admin",
//           NickName: data?.["username"] || "管理员",
//           RoleCode: "admin",
//           Token: "mock_access_token_" + Date.now(),
//           Expiration: new Date(Date.now() + 24 * 60 * 60 * 1000).toString() // 24小时后过期
//         },
//         Message: "登录成功"
//       };
//
//       const expire = dateAdd("m", -5, new Date(mockRes.Data.Expiration));
//       resolve({
//         success: true,
//         data: {
//           avatar: mockRes.Data.Avatar,
//           username: mockRes.Data.UserName,
//           nickname: mockRes.Data.NickName,
//           roles: [mockRes.Data.RoleCode],
//           permissions: [],
//           accessToken: mockRes.Data.Token,
//           refreshToken: mockRes.Data.Token,
//           expires: dayjs(expire).format("YYYY-MM-DD HH:mm:ss")
//         },
//         info: mockRes.Message
//       });
//     }, 500); // 500ms延迟
//   });
// };
/** 刷新`token` */
export const refreshTokenApi = (data?: object) => {
  return new Promise<RefreshTokenResult>((resolve, reject) => {
    http
      .request("post", changeHttpLink("/api/System/refresh_token"), {
        data
      })
      .then((res: any) => {
        if (res.Success) {
          const expire = dateAdd("m", -5, new Date(res.Data.Expiration));
          resolve({
            success: true,
            //@ts-ignore
            data: {
              accessToken: res.Data.Token,
              refreshToken: res.Data.Token,
              //@ts-ignore
              expires: dayjs(expire).format("YYYY-MM-DD HH:mm:ss")
            }
          });
        } else {
          resolve({
            success: false,
            //@ts-ignore
            data: {}
          });
        }
      })
      .catch(err => {
        reject(err);
      });
  });
};
